package com.ray.service;

import com.ray.dao.UserDao;
import com.ray.pojo.User;
import com.ray.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;
import java.util.Map;

public class UserServiceImpl implements UserService
{
    /**
     * @return
     */
    @Override
    public List<User> getUserList()
    {

        try (SqlSession sqlSession = SqlSessionUtil.getSqlSession())
        {
            UserDao mapper = sqlSession.getMapper(UserDao.class);
            List<User> userList = mapper.getUserList();
            return userList;
        }
    }

    /**
     * @param user
     * @return
     */
    @Override
    public int addUser(User user)
    {
        try (SqlSession sqlSession = SqlSessionUtil.getSqlSession())
        {

            UserDao mapper = sqlSession.getMapper(UserDao.class);
            int result = mapper.addUser(user);
            sqlSession.commit();
            sqlSession.close();
            return result;
        }
    }

    /**
     * @param user
     * @return
     */
    @Override
    public int updateUser(User user)
    {
        try (SqlSession sqlSession = SqlSessionUtil.getSqlSession())
        {
            UserDao mapper = sqlSession.getMapper(UserDao.class);
            int result = mapper.updateUser(user);
            sqlSession.commit();
            sqlSession.close();
            return result;
        }
    }

    /**
     * @param id
     * @return
     */
    @Override
    public int deleteUser(int id)
    {
        try (SqlSession sqlSession = SqlSessionUtil.getSqlSession())
        {
            UserDao mapper = sqlSession.getMapper(UserDao.class);
            int result = mapper.deleteUser(id);
            sqlSession.commit();
            sqlSession.close();
            return result;
        }
    }

    @Override
    public List<User> getUser(Integer id, String name)
    {
        try (SqlSession sqlSession = SqlSessionUtil.getSqlSession())
        {
            UserDao mapper = sqlSession.getMapper(UserDao.class);
            List<User> userList = mapper.getUser(id, name);
            return userList;
        }
    }

    @Override
    public List<User> getUserByMap(Map<String, Object> params)
    {
        try (SqlSession sqlSession = SqlSessionUtil.getSqlSession())
        {
            UserDao mapper = sqlSession.getMapper(UserDao.class);
            List<User> userList = mapper.getUserByMap(params);
            return userList;
        }
    }

    /**
     * @param id
     * @return
     */
    @Override
    public User getUserById(long id)
    {
        try (SqlSession sqlSession = SqlSessionUtil.getSqlSession())
        {
            UserDao mapper = sqlSession.getMapper(UserDao.class);
            User user = mapper.getUserById(id);
            return user;
        }
    }


}
